package net.sx.minemodule.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.homegoods.aroutercomment.ARouterPath;
import com.kedll.library.dialog.ECAlertDialog;
import com.kedll.library.dialog.ECProgressDialog;
import com.kedll.library.util.BindingUtil;
import com.kedll.library.util.Log;
import com.kedll.library.util.ToastUtil;
import com.kedll.library.util.UIUtil;

import net.sx.minemodule.MineApiUtils;
import net.sx.minemodule.R;
import net.sx.minemodule.databinding.MineItemMineOrderBinding;
import net.sx.minemodule.mvp.activities.MineOrderLogisticsActivity;
import net.sx.minemodule.mvp.bean.GoodsBean;
import net.sx.minemodule.mvp.bean.OrderBean;

import java.util.List;

/**
 * 描述:  订单 item 单个商品
 * author:胡邦茂
 * CreateDate: 2019/7/7 11:30
 */

public class MineOrderGoodView extends LinearLayout {

    private MineItemMineOrderBinding mBinding;

    private OrderBean mModel;

    public MineOrderGoodView(Context context) {
        this(context, null);
    }

    public MineOrderGoodView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MineOrderGoodView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        mBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.mine_item_mine_order, this, true);
    }

    public void setData(OrderBean model) {
        mModel = model;

        //del hubangmao 暂时注释 显示商家名称 +图片 (最新设计图)
        //setHeadImage(Constant.SERVER_URL + model.getShopImg());
        //setStoreName(model.getStopName());

        setOrderType(model.getOrderType());
        List<GoodsBean> p = model.getOrderProducts();
        if (!p.isEmpty()) {
            //设置 商品信息
            setProducts(p.get(0));
        }


        //3、点击事件部分
        mBinding.tvRightButtonOrderMine.setOnClickListener(mListener);
        mBinding.tvLeftButtonOrderMine.setOnClickListener(mListener);
        mBinding.tvLeftThreeOrderMine.setOnClickListener(mListener);
        mBinding.tvLeftFourOrderMine.setOnClickListener(mListener);
        int drawA541c9 = R.drawable.mine_bg_2_a541c9, drawEeeeee = R.drawable.mine_bg_2_eeeeee;
        int colorA541c9 = R.color.color_a541c9, color333 = R.color.color_333333;

        //4、按钮状态部分
        switch (model.getOrderType()) {
            case "待支付":
                mBinding.tvRightButtonOrderMine.setTag(0);
                mBinding.tvRightButtonOrderMine.setText("付款");
                mBinding.tvRightButtonOrderMine.setBackgroundResource(drawA541c9);
                mBinding.tvRightButtonOrderMine.setTextColor(getResources().getColor(colorA541c9));

                mBinding.tvLeftButtonOrderMine.setTag(1);
                mBinding.tvLeftButtonOrderMine.setText("取消订单");
                mBinding.tvLeftButtonOrderMine.setBackgroundResource(drawEeeeee);
                mBinding.tvLeftButtonOrderMine.setTextColor(getResources().getColor(color333));
                break;
            case "已支付":
                mBinding.tvRightButtonOrderMine.setTag(2);
                mBinding.tvRightButtonOrderMine.setText("联系客服");
                mBinding.tvLeftButtonOrderMine.setVisibility(GONE);
                mBinding.tvRightButtonOrderMine.setBackgroundResource(drawEeeeee);
                break;
            case "已发货":
                mBinding.tvRightButtonOrderMine.setTag(3);
                mBinding.tvRightButtonOrderMine.setText("确认收货");
                mBinding.tvRightButtonOrderMine.setBackgroundResource(drawA541c9);
                mBinding.tvRightButtonOrderMine.setTextColor(getResources().getColor(colorA541c9));

                mBinding.tvLeftButtonOrderMine.setTag(4);
                mBinding.tvLeftButtonOrderMine.setText("查看物流");
                mBinding.tvLeftButtonOrderMine.setBackgroundResource(drawEeeeee);
                mBinding.tvLeftButtonOrderMine.setTextColor(getResources().getColor(color333));
                break;

            case "已签收":

                mBinding.tvLeftButtonOrderMine.setTag(4);
                mBinding.tvLeftButtonOrderMine.setVisibility(VISIBLE);
                mBinding.tvLeftButtonOrderMine.setText("查看物流");
                mBinding.tvLeftButtonOrderMine.setBackgroundResource(drawEeeeee);
                mBinding.tvLeftButtonOrderMine.setTextColor(getResources().getColor(color333));

                mBinding.tvLeftThreeOrderMine.setVisibility(GONE);
                mBinding.tvRightButtonOrderMine.setVisibility(GONE);
                //del bangmao.hu
                //mBinding.tvLeftFourOrderMine.setVisibility(VISIBLE);
                //mBinding.tvLeftFourOrderMine.setText("更多");
                //mBinding.tvLeftFourOrderMine.setTextColor(getResources().getColor(color333));
                //mBinding.tvLeftFourOrderMine.setTag(6);
                break;
            case "维权中":
                mBinding.tvLeftThreeOrderMine.setVisibility(GONE);
                break;
            case "退款成功":
                mBinding.tvRightButtonOrderMine.setText("再次购买");
                mBinding.tvRightButtonOrderMine.setTag(7);
                mBinding.tvRightButtonOrderMine.setBackgroundResource(drawA541c9);
                mBinding.tvRightButtonOrderMine.setTextColor(getResources().getColor(colorA541c9));
                mBinding.tvLeftButtonOrderMine.setText("取消订单");
                mBinding.tvLeftButtonOrderMine.setBackgroundResource(drawEeeeee);
                mBinding.tvLeftButtonOrderMine.setTextColor(getResources().getColor(color333));
                mBinding.tvLeftButtonOrderMine.setTag(1);
                break;

        }

    }

    private void setProducts(GoodsBean goodsBean) {
        BindingUtil.loadImage(mBinding.ivGoodsImgMineOrder, goodsBean.getPic(), getContext().getResources().getDrawable(R.drawable.load_error), null);
        mBinding.tvGoodsNameMineOrder.setText(goodsBean.getProductName());
        mBinding.tvAttr.setText(getAttrText(goodsBean));
        mBinding.tvGoodsNum.setText(String.valueOf("x " + goodsBean.getNum()));

        //设置价格
        SpannableString s = new SpannableString("¥ " + goodsBean.getSalePrice());
        //缩小0.7
        RelativeSizeSpan start = new RelativeSizeSpan(0.7f);
        s.setSpan(start, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        int index = s.toString().indexOf(".");
        if (index != -1) {
            s.setSpan(start, index, s.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        mBinding.tvMoney.setText(s);

        if (!TextUtils.isEmpty(goodsBean.getPromotionName())) {
            mBinding.tvIntegralHint.setVisibility(VISIBLE);
            mBinding.tvIntegralHint.setText(goodsBean.getPromotionName());
        }
        mBinding.tvPackageMail.setVisibility(VISIBLE);
        mBinding.tvPackageMail.setText(goodsBean.isDistributionType() ? "包邮" : "不包邮");

    }


    public String getAttrText(GoodsBean goodsBean) {
        StringBuilder attrText = new StringBuilder();
        List<GoodsBean.AttrsBean> attrs = goodsBean.getAttrs();
        if (attrs.isEmpty()) {
            return "";
        }
        for (GoodsBean.AttrsBean item : attrs) {
            attrText.append(item.getName()).append("：").append(item.getValue()).append("\t");
        }
        return attrText.toString();
    }

    private Listener mListener = new Listener();

    class Listener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            Log.e("hbm", view.getTag());
            if (view.getTag() == null) {
                return;
            }

            switch ((Integer) view.getTag()) {
                case 0://付款
                    //ARouter.getInstance().build(ARouterPath.PATH_MINE_ORDER_PAY).withInt("type", 0).withString("price", mModel.getGoodsAllMoney()).withString("orderSid", mModel.getTsid()).navigation();

                    break;
                case 1://取消订单
                    showClearOrder();
                    break;
                case 2://联系客服
                    collCust();
                    break;
                case 3://确认收货
                    showObtainDialog();
                    break;
                case 4:
                    //查看物流
                    ARouter.getInstance()
                            .build(ARouterPath.PATH_MINE_ORDER_LOGISTICS)
                            .withInt(MineOrderLogisticsActivity.KEY_ORDER_ID, mModel.getOrderId())
                            .navigation();
                    break;
                case 6://更多

                    break;
                case 7://再次购买

                    break;
            }
        }
    }

    /**
     * 描述:  拨打客服电话
     * author:胡邦茂
     * CreateDate: 2019/7/5 19:36
     */
    private void collCust() {
        showLoading();
        MineApiUtils.getServicePhoneNumber(mModel.getOrderId()
                , phone -> {
                    closeLoading();
                    if (!TextUtils.isEmpty(phone)) {
                        //查询成功 调起拨号
                        call(phone);
                    } else {
                        ToastUtil.showToast(phone);
                    }
                }, throwable -> {
                    ToastUtil.showToast(throwable.getMessage());
                    closeLoading();
                });

    }

    /**
     * 描述:  调用拨号界面
     * author:胡邦茂
     * CreateDate: 2019/7/5 19:36
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getContext().startActivity(intent);
    }

    /**
     * 描述:  确认收货
     * author:胡邦茂
     * CreateDate: 2019/7/5 19:36
     */
    private void showObtainDialog() {
        ECAlertDialog alert = ECAlertDialog.buildAlert(getContext(), "确认收货吗 ?", "我已收到商品", "未收到商品"
                , (dialog, which) -> {
                    requestObtain(1);
                }, (dialog, which) -> {
                    requestObtain(2);
                });
        alert.setTitle(" ");
        alert.show();

    }

    private void requestObtain(int type) {
        showLoading();
        MineApiUtils.obtainGoods(mModel.getOrderId(), type, res -> {
            closeLoading();
            //刷新
            if (res > 0) {
                ToastUtil.showToast("成功");
                mModel.setStatus(3);
                mModel.notifyChange();
            }
        }, th -> {
            closeLoading();
            ToastUtil.showToast(th.getMessage());
        });
    }

    class VH {
        View view;
        ImageView ivClose;
        LinearLayout llContent;
        TextView tvSubmit;
        String[] data;
    }

    private AppPopupWidows<VH> mClearPopup;
    private ECProgressDialog mHintDialog;

    private void showLoading() {
        if (mHintDialog == null) {
            mHintDialog = new ECProgressDialog(getContext()).setPressText("提交中");
        }
        mHintDialog.show();
    }

    private void closeLoading() {
        if (mHintDialog != null) {
            mHintDialog.dismiss();
        }
    }

    /**
     * 描述:  提交退货
     * author:胡邦茂
     * CreateDate: 2019/7/5 19:36
     */
    private void showClearOrder() {
        if (mClearPopup == null) {
            mClearPopup = new AppPopupWidows<>((Activity) getContext(), R.layout.mine_popup_clear_order);
            mClearPopup.setAnimStyle(R.style.timepopwindow_anim_style).setHeight(400);

            mClearPopup.builder(new AppPopupWidows.InitListener<VH>() {
                @Override
                public void onClick(View v) {
                    int id = v.getId();
                    //1、关闭
                    if (id == R.id.iv_clear) {
                        mClearPopup.dismiss();
                        return;
                    }
                    VH vh = mClearPopup.getViewHoder();

                    //2、提交退货
                    if (id == R.id.tv_submit) {
                        if (!vh.tvSubmit.isSelected()) {
                            ToastUtil.showToast("请选择", Gravity.TOP);
                            return;
                        }
                        mClearPopup.dismiss();
                        showLoading();
                        MineApiUtils.clearMyOrder(mModel.getOrderId(), (Integer) vh.tvSubmit.getTag(), "", msg -> {
                            ToastUtil.showToast(msg);
                            mHintDialog.dismiss();
                            //刷新
                            mModel.setStatus(6);
                            mModel.notifyChange();
                        }, th -> {
                            ToastUtil.showToast(th.getMessage());
                            closeLoading();
                        });
                        return;
                    }

                    //3、交互选中
                    for (int i = 0; i < vh.llContent.getChildCount(); i++) {
                        View view = vh.llContent.getChildAt(i);
                        ImageView status = view.findViewById(R.id.iv_status);
                        if (view.getTag() == v.getTag()) {
                            status.setImageResource(status.isSelected() ? R.mipmap.ic_un_checked : R.mipmap.ic_checked);
                            status.setSelected(!status.isSelected());
                            vh.tvSubmit.setSelected(status.isSelected());
                            vh.tvSubmit.setTag(vh.tvSubmit.isSelected() ? view.getTag() : 0);
                        } else {
                            status.setSelected(false);
                            status.setImageResource(R.mipmap.ic_un_checked);
                        }
                    }

                    vh.tvSubmit.setBackgroundResource(
                            vh.tvSubmit.isSelected() ?
                                    R.drawable.shape_round_a541c9_20
                                    : R.drawable.shape_round_color_bbbbbb_20);

                }

                @Override
                public VH bindView(View v) {
                    VH vh = new VH();
                    vh.view = v;
                    vh.ivClose = v.findViewById(R.id.iv_clear);
                    vh.data = getContext().getResources().getStringArray(R.array.mine_array_clear_order_item);
                    vh.llContent = v.findViewById(R.id.ll_content);
                    vh.tvSubmit = v.findViewById(R.id.tv_submit);

                    vh.ivClose.setOnClickListener(this);
                    vh.tvSubmit.setOnClickListener(this);
                    for (int i = 0; i < vh.data.length; i++) {
                        View view = View.inflate(getContext(), R.layout.mine_popup_clear_order_item, null);
                        TextView name = view.findViewById(R.id.tv_name);
                        name.setText(vh.data[i]);
                        vh.llContent.addView(view);
                        view.getLayoutParams().height = UIUtil.dip2px(40);
                        view.setOnClickListener(this);
                        view.setTag(i);
                    }
                    return vh;
                }

                @Override
                public void initViewData(VH data, View v) {

                }
            })
                    .setOnDismissListener(() -> {
                        mClearPopup.setBackgroundAlpha(1f);
                    });
        }

        mClearPopup.setBackgroundAlpha(0.5f).show();
    }

    /**
     * 设置头像
     *
     * @param headUrl
     */
    private void setHeadImage(String headUrl) {
        BindingUtil.loadCircleImage(mBinding.ivStoreImgMineOrder, headUrl, getContext().getResources().getDrawable(R.drawable.load_error));

    }

    /**
     * 设置店铺名
     *
     * @param storeName
     */
    private void setStoreName(String storeName) {
        mBinding.tvStoreNameMineOrder.setText(storeName);
    }

    /**
     * 订单类型
     *
     * @param orderType
     */
    private void setOrderType(String orderType) {
        mBinding.tvOrderType.setText(orderType);
    }


}
